package com.ken.mqbase.limit;

import com.ken.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 自定义的消费限流 消费者
 * Created by renchongyu on 2018/11/16.
 */
public class ConsumerLimit {

    public static void main(String[] args) throws Exception {
        //1.创建一个ConnectionFactory
        ConnectionFactory conn = new ConnectionFactory();
        conn.setHost(RabbitConstant.RABBITMQ_IP);
        conn.setPort(RabbitConstant.RABBITMQ_PORT);
        conn.setUsername(RabbitConstant.RABBITMQ_USER_NAME);
        conn.setPassword(RabbitConstant.RABBITMQ_USER_PASSWORD);
        conn.setVirtualHost(RabbitConstant.RABBITMQ_VIRTUAL_HOST);

        //2.通过连接工厂连接
        Connection connection = conn.newConnection();

        //3.通过连接创建一个channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_qos_exchange";
        String queueName = "test_qos_queue";
        String routingKey = "qos.#";

        channel.exchangeDeclare(exchangeName,"topic",true,false,null);
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchangeName,routingKey);

        //1.限流方式 第一件事就是 autoAck 设置为 false
        /**
         * prefetchSize 默认为0
         * prefetchCount 处理条数 一般1--3条
         * global 手工签收一定要设置为false
         */
        channel.basicQos(0,1,false);

        channel.basicConsume(queueName,false,new MyLimit(channel));
    }
}
